package com.piesat.quake.business.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.piesat.common.exception.BadRequestException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piesat.security.service.dto.UserDto;
import com.piesat.quake.business.system.mapper.SysRoleMapper;
import com.piesat.quake.business.system.mapper.SysUserMapper;
import com.piesat.quake.business.system.model.SysRole;
import com.piesat.quake.business.system.model.SysUser;
import com.piesat.quake.business.system.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-04-22
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMapper roleMapper;
    private final SysUserMapper userMapper;

    @Override
    public List<GrantedAuthority> mapToGrantedAuthorities(UserDto userDto) {
        SysRole role = Optional.ofNullable(userDto.getRoleId() == null ? null : roleMapper.selectById(userDto.getRoleId())).orElseThrow(() -> new BadRequestException("该用户没有相应的角色，请联系管理员给用户赋予角色"));
        return List.of(role).stream().map(SysRole::getRoleName).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }


    @Override
    public void verification(Set<String> ids) {
        if (userMapper.selectCount(new LambdaQueryWrapper<SysUser>().in(SysUser::getRoleId, ids)) > 0) {
            throw new BadRequestException("所选角色存在用户关联，请解除关联后再试！");
        }
    }
}
